
import { HTTP } from '../../../utils/http.js'
import api from '../../../utils/api.js'
import { config } from '../../../utils/config'
import utils from "../../../utils/util"
let http = new HTTP()
var app = getApp();


Page({
  /**
   * 页面的初始数据
   */
  data: {
    imgUrl: config.imgUrl,
    payBtn: true,
    maskShow: false,
    picPath: [],
    picList: [],
    typeIndex: 0,
    typeArray: [{ type: 1, applyType: '退款' }, { type: 2, applyType: '退货' }],
    applyIndex: 0,
    textLength: 0,
    textArea: "",
    applyType: 1,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let order_no = options.order;
    let paymeth = options.paymeth;
    let reftype = options.reftype;
    this.setData({
      order_no,
      pay_method: paymeth,
      reftype
    })
    this.inteGetReasonList();
  },
  preventD() {
    return
  },
  bindPickerChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    let index = e.detail.value;
    let typeArray = this.data.typeArray;
    let typeId = typeArray[index].type
    this.setData({
      typeIndex: index,
      applyType: typeId
    })
  },
  bindReasonChange: function (e) {
    let applyIndex = e.detail.value
    console.log('picker发送选择改变，携带值为', e.detail.value)
    let reasonList = this.data.reasonList;
    let reasonId = reasonList[applyIndex].id
    this.setData({
      applyIndex,
      reasonId
    })
  },
  textInput(e) {
    let textArea = e.detail.value;
    let textLength = textArea.length;
    this.setData({
      textLength,
      textArea
    })
  },
  commentAdd() {
    let that = this;
    if (this.data.textArea == '') {
      wx.showToast({
        title: '请填写申请原因',
        icon: 'none',
        duration: 1500
      })
      return;
    }
    // 当时退款时做判断
    if (this.data.reftype && !this.data.applyType) {
      this.setData({
        applyType: 1
      })
    }
    let data = {
      order_no: that.data.order_no,
      type: that.data.applyType,
      reason: that.data.reasonId,
      reason_details: that.data.textArea,
      imgs: that.data.picPath
    }

    http.request({
      url: api.inteApply,
      method: 'POST',
      data: data,
      success: (res) => {
        if (res.code == 200) {
          wx.showToast({
            title: '申请成功',
            icon: 'success',
            duration: 1500
          })
          const pages = getCurrentPages()
          const prevPage = pages[pages.length - 2]
          prevPage.setData({
            refresh: true
          })

          setTimeout(() => {
            wx.navigateTo({
              url: `/pages/refund/pomDetail/pomDetail?order=${res.data.service_no}`
            })
          }, 1500);
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none',
            duration: 1500
          });
          return;
        }
      },
      fail: (res) => { }
    })
  },
  inteGetReasonList() {
    utils.getInfo(api.inteGetReasonList, "GET", {}).then(res => {
      let reasonArr = [];
      for (const key in res) {
        reasonArr.push({ id: key, reason: res[key] });
      }
      this.setData({
        reasonList: reasonArr,
        reasonId: reasonArr[0].id ? reasonArr[0].id : 0,
      })
    })
  },
  // 获取订单详情
  getOrderDetail() {
    let that = this;
    wx.showLoading({ title: '加载中' })
    let order_no = this.data.order_no;
    http.request({
      url: api.integralOrderDetails,
      method: 'GET',
      data: {
        order_no: order_no
      },
      success: (res) => {
        wx.hideLoading();
        let result = res.data
        if (res.code == 200) {
          that.setData(result)

          if (result.status == 1) {
            timer = setInterval(function () {
              that.showtime()
            }, 1000);
          }
        }
      },
      fail: (res) => {
      }
    })
  },

  //上传图片开始
  chooseImg: function (e) {
    var that = this
    let picList = this.data.picList
    let picPath = this.data.picPath
    if (picList.length < 3) {
      wx.chooseImage({
        count: 3 - picList.length, // 最多可以选择的图片张数，默认9
        sizeType: ['compressed'], // original 原图，compressed 压缩图，默认二者都有
        sourceType: ['album', 'camera'], // album 从相册选图，camera 使用相机，默认二者都有
        success: function (res) {
          // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
          var tempFilePaths = res.tempFilePaths;
          wx.showLoading({ title: '上传中' })
          for (var i = 0; i < tempFilePaths.length; i++) {
            // pics.push(tempFilePaths[i]);
            wx.uploadFile({
              url: config.debug_url + api.uploadFiles, //仅为示例，非真实的接口地址
              filePath: tempFilePaths[i],
              name: 'file',
              formData: {
                // token : wx.getStorageInfoSync('token')
              },
              success(res) {

                if (res.statusCode == 200) {
                  let result = JSON.parse(res.data);
                  // console.log('result',result.data.img ,result.data.path);

                  if (result.data.img && result.data.path) {
                    picList.push(result.data.img);  //前台展示
                    picPath.push(result.data.path); //传给后台
                    that.setData({
                      picList, picPath
                    })
                  } else {
                    wx.showToast({
                      title: '上传错误',
                      icon: 'none',
                      duration: 1500
                    });
                  }
                }
              },
              fail() {
              },
              complete() {
                wx.hideLoading();
              }
            })
          }
        },
      });
    } else {
      wx.showToast({
        title: '最多上传3张图片',
        icon: 'none',
        duration: 1500
      });
    }
  },
  // 删除图片
  deleteImg: function (e) {
    var that = this;
    var picList = this.data.picList;
    var picPath = this.data.picPath
    var index = e.currentTarget.dataset.index;
    picList.splice(index, 1);
    picPath.splice(index, 1)
    this.setData({
      picPath, picList
    })
  },
  // 预览图片
  previewImg1: function (e) {
    //获取当前图片的下标
    var index = e.currentTarget.dataset.index;
    //所有图片
    var picList = this.data.picList;
    wx.previewImage({
      //当前显示图片
      current: picList[index],
      //所有图片
      urls: picList
    })
  },
  showtime() {
    let expire_time = this.data.overtime
    var nowtime = new Date(); //获取当前时间
    let expireFormat = expire_time.replace(/-/g, '/');
    // console.log('expireFormat',expireFormat);
    let endtime = new Date(expireFormat);  //定义结束时间
    var lefttime = endtime.getTime() - nowtime.getTime(),  //距离结束时间的毫秒数
      leftd = Math.floor(lefttime / (1000 * 60 * 60 * 24)),  //计算天数
      lefth = Math.floor(lefttime / (1000 * 60 * 60) % 24),  //计算小时数
      leftm = Math.floor(lefttime / (1000 * 60) % 60),  //计算分钟数
      lefts = Math.floor(lefttime / 1000 % 60);  //计算秒数
    let timeOut = leftm + "分" + lefts + '秒';
    if (leftm == 0 && lefts == 0) {
      this.cancelOrderTime();
    } else {
      this.setData({
        timeOut
      })
    }
  },
  /*申请退款*/
  refund() {

    let that = this;
    wx.showModal({
      title: '提示',
      content: '确定申请退款？',
      confirmColor: '#EA5D56',
      success(res) {
        if (res.confirm) {

          http.request({
            url: api.refundOrder,
            method: "POST",
            data: {
              order_no: that.data.order_no,
              refund_cause: '商品质量有问题'
            },
            success: (res) => {
              console.log(res);
              if (res.code == 200) {
                console.log('申请退款成功');
                that.getOrderDetail();
                // 给上一页传递数据
                const pages = getCurrentPages()
                const prevPage = pages[pages.length - 2]
                prevPage.setData({
                  refundOrderBack: that.data.order_no
                })
              }
            },
            fail: (res) => {
            }
          })
        } else if (res.cancel) {
          return;
        }
      }
    })
  },
  copyBtn() {
    var that = this;
    wx.setClipboardData({
      //准备复制的数据
      data: that.data.username + that.data.phone + that.data.address,
      success: function (res) {
        wx.showToast({
          title: '复制成功',
          icon: 'none'
        });
      }
    });
  },
  //删除订单
  deleteOrder() {
    let that = this;
    let order_no = that.data.order_no;
    const pages = getCurrentPages()
    const prevPage = pages[pages.length - 2] // 上一页// 调用上一个页面的setData 方法，将数据存储

    wx.showModal({
      title: '提示',
      content: '确定删除订单',
      confirmColor: '#EA5D56',
      success(res) {
        if (res.confirm) {
          prevPage.setData({
            deleteOrder: order_no
          })
          wx.navigateBack({
            delta: 1
          })
        } else if (res.cancel) {
          return;
        }
      }
    })

  },
  payOrder(e) {
    if (!this.data.payBtn) {
      return false
    } else {
      this.setData({
        payBtn: false
      })
    }
    let that = this
    let order_no = this.data.order_no;
    return new Promise((resolve, reject) => {
      http.request({
        url: api.integralPay,
        data: {
          order_no
        },
        success: res => {
          if (res.msg && res.error_code) {
            wx.showToast({
              title: res.msg,
              icon: 'none',
              duration: 1500
            });
            that.setData({
              payBtn: true
            })
            return;
          }

          if (res.code == 200) {
            let data = res.data
            // 调起微信支付
            wx.requestPayment({
              'timeStamp': data.timeStamp,
              'nonceStr': data.nonceStr,
              'package': data.package,
              'signType': 'MD5',
              'paySign': data.paySign,
              'success': function (res) {
                console.log('支付成功', res);
                wx.setStorageSync("select-menus", '')
                // 给上一页传递数据
                const pages = getCurrentPages()
                const prevPage = pages[pages.length - 2]
                prevPage.setData({
                  payOrderBack: order_no
                })
              },
              'fail': function (res) {
                that.setData({
                  payBtn: true
                })
                console.log('支付失败', res);
                reject(res)
              },
              'complete': function (res) {
                that.payNotify(order_no)
              }
            })
          }
        },
        fail(res) {
        }
      })
    })
  },
  // 支付接口调用完成之后订单查询
  payNotify(order_no) {
    let that = this;
    console.log('支付回调');
    http.request({
      url: api.integralPayNotify,
      method: "POST",
      data: {
        order_no: order_no
      },
      success: (res) => {
        console.log(res);
        if (res.code == 200) {
          // 支付成功需要修改菜篮
          that.setData({
            payBtn: true,
          })
          //支付成功更改缓存payList
          that.getOrderDetail();
        }
      },
      fail: (res) => {
      }
    })

  },

  // 取消订单
  cancelOrder() {
    let that = this;
    let order_no = that.data.order_no;
    wx.showModal({
      title: '提示',
      content: '确定取消订单',
      confirmColor: '#EA5D56',
      success(res) {
        if (res.confirm) {
          http.request({
            url: api.integralCancelOrder,
            method: "POST",
            data: {
              order_no
            },
            success: (res) => {
              console.log(res);
              if (res.code == 200) {
                that.getOrderDetail();
                // 给上一页传递数据
                const pages = getCurrentPages()
                const prevPage = pages[pages.length - 2]
                prevPage.setData({
                  cancelOrderBack: order_no
                })
              }
            },
            fail: (res) => {
            }
          })
        } else if (res.cancel) {
          return;
        }
      }
    })

  },

  // 取消订单
  cancelOrderTime() {
    let that = this;
    let order_no = that.data.order_no;
    http.request({
      url: api.integralCancelOrder,
      method: "POST",
      data: {
        order_no
      },
      success: (res) => {
        console.log(res);
        if (res.code == 200) {
          clearInterval(timer);
          that.getOrderDetail();
          // 给上一页传递数据
          const pages = getCurrentPages()
          const prevPage = pages[pages.length - 2]
          prevPage.setData({
            cancelOrderBack: order_no
          })
        }
      },
      fail: (res) => {
      }
    })
  },
  // 电话
  service(e) {
    let phone = e.currentTarget.dataset.phone;
    console.log(phone);
    wx.makePhoneCall({
      phoneNumber: phone.toString()
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  goAddComment() {
    app.globalData.comproduct = {
      product_id: this.data.orderproduct.product_id,
      order_no: this.data.order_no,
      pay_method: this.data.pay_method,
      orderproduct: this.data.orderproduct.product_info.productInfo
    }
    wx.navigateTo({
      url: '/pages/pointsMall/postComments/postComments'
    })
  },
  CommentList(e) {
    let id = this.data.orderproduct.product_id
    wx.navigateTo({
      url: '/pages/pointsMall/comments/comments?id=' + id
    })
  },
  onReady: function () {

  },

  confirmReceipt(e) {
    let that = this
    let order_no = this.data.order_no;
    wx.showModal({
      title: '提示',
      content: '确定收货',
      confirmColor: '#EA5D56',
      success(res) {
        if (res.confirm) {

          http.request({
            url: api.integralConfirmReceipt,
            method: "POST",
            data: {
              order_no
            },
            success: (res) => {
              console.log(res);
              if (res.code == 200) {

                // 给上一页传递数据
                const pages = getCurrentPages()
                const prevPage = pages[pages.length - 2]
                prevPage.setData({
                  receiptOrderBack: order_no
                })
                that.getOrderDetail();
              }
            },
            fail: (res) => {
            }
          })
        } else if (res.cancel) {
          return;
        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getOrderDetail();
  },

  closeMask() {
    this.setData({
      maskShow: false
    })
  },

  openMask() {
    this.setData({
      maskShow: true
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    clearInterval(timer)
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})